<template>
    <section id="cicd-newdeployment">
        <el-col :span="16">
            <el-alert
                    title="上线任务注意项"
                    type="warning"
                    show-icon
                    style="margin-bottom: 10px"
                    :closable="false"
            >
                <template >
                    <ol>
                        <li>上线项目和上线脚本将按照选择顺序执行</li>
                        <li>先执行脚本，再发布项目</li>
                        <li>默认任务执行期间，脚本执行或者项目发布任何出错，将终止整个任务的自动执行，需运维人工介入</li>
                    </ol>
                </template>
            </el-alert>
        <el-card style="background-color: #FAFAFA;">
    <el-form ref="newjob" :model="newjob" label-width="80px" style="width: 90%"  size="small" :rules="addDeployJobRules">
        <el-form-item label="任务标题"  prop="title">
            <el-col :span="8">
                <el-input v-model="newjob.title" placeholder="请输入标题"></el-input>
            </el-col>

        </el-form-item>
        <el-form-item label="任务内容"  prop="jobcontent">
            <el-col :span="24">
                <el-input
                        type="textarea"
                        :autosize="{ minRows: 1, maxRows: 10}"
                        placeholder="请输入上线主要内容"
                        v-model="newjob.jobcontent"></el-input>
            </el-col>

        </el-form-item>
        <el-form-item label="测试报告"  prop="testRePortCheckRules">
            <el-col :span="8">
                <el-upload
                        style="display: inline"
                        class="upload-demo"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        accept=".xlsx , .xls"
                        :show-file-list="true"
                        :limit="1"
                        :on-change="fileChange"
                        :on-remove="fileChange"
                        :on-exceed="handleExceed"
                        :before-upload="beforeAvatarUpload"
                        :on-success="handleAvatarSuccess"
                        :on-error="handleAvatarError"
                        :file-list="testReportList">
                    <el-button size="mini" type="warning" plain>点击上传</el-button>
                    <div slot="tip" class="el-upload__tip" style="display: inline;font-size: 5px" >&nbsp;&nbsp;&nbsp;&nbsp;上传excel报告，且不超过 <strong >2M</strong></div>

                </el-upload>
            </el-col>
        </el-form-item>
        <el-form-item label="上线时间" prop="onlineDateTime">
            <el-col :span="8">
                <el-time-select placeholder="选择时间" v-model="newjob.onlineTime" style="width: 100%;"
                                :picker-options="{
                                 start: '18:30',
                                 step: '00:30',
                                 end: '24:00'
                                 }"
                ></el-time-select>
            </el-col>
        </el-form-item>

        <el-form-item label="上线项目" prop="onlineItems">
            <el-col :span="8">
                <el-select v-model="newjob.onlineItems" placeholder="请选择上线项目" multiple style="width: 100%" @focus="chooseItems">
                    <el-option v-for="db in this.itemsChoice " :label=db.name :value=db.name></el-option>
                </el-select>
            </el-col>
        </el-form-item>



        <el-form-item label="上线脚本" prop="dbChooseUniqueRules">
            <el-col :span="24">
                <template>
                    <section>
                        <el-tag
                                :key="tag"
                                v-for="(tag,index) in newjob.databaseTags"
                                closable
                                :disable-transitions="false"
                                size="medium"
                                @close="handleClose(index)">
                            {{tag}}
                        </el-tag>

                        <el-select
                                v-if="selectVisible"
                                v-model="selectVaule"
                                ref="saveTagInput"
                                @change="handleSelectConfirm"
                                placeholder="请选择数据库"
                                style="width: 150px"
                                @focus="chooseDbs"
                        >
                            <el-option v-for="db in this.dbChoice " :label=db.name :value=db.name></el-option>
                        </el-select>
                        <el-button  class="button-new-tag" size="mini" @click="showSelect" icon="el-icon-plus">Sql Script</el-button>
                    </section>
                </template>
            </el-col>
        </el-form-item>



        <el-form-item :label="db"   v-for="(db , index) in newjob.databaseTags" >
            <el-col :span="24">
                <el-input
                        type="textarea"
                        :autosize="{ minRows: 2, maxRows: 10}"
                        placeholder="请输入SQL格式语句"
                        v-model="newjob.databaseSql[index]">
                </el-input>
            </el-col>

        </el-form-item>





        <el-form-item>
            <el-button type="primary" @click="createDeployJob('newjob')">立即创建</el-button>
            <el-button @click="cancelCreate">取消</el-button>



        </el-form-item>
    </el-form>
        </el-card>
        </el-col>
    </section>
</template>

<script>
    import { AddDeployJob,getDbList,getDeployItems } from '../../api/api'
    export default {
        data() {
            var dbChooseUnique = (rule, value, callback) => {

                let self = this
                let repeat = self.isRepeat(self.newjob.databaseTags)
                let empty = self.containEmpty(self.newjob.databaseSql)



                if (repeat) {
                    callback(new Error('请勿选择重复数据库'));
                } else if (empty) {
                    callback(new Error('请填写SQL'));
                } else {
                    callback()
                }

            };
            var reportUpload = (rule, value, callback) => {

                let self = this

                if (self.testReportList.length !== 1) {
                    callback(new Error('请上传测试报告'));
                } else {
                    callback()
                }

            };
            return {
                newjob: {
                    title: "",
                    jobcontent: "",
                    onlineTime: "",
                    onlineItems: "",
                    databaseTags: [],
                    databaseSql:[],

                },
                testReportList: [],   //测试报告


                addDeployJobRules: {
                    title: [
                        { required: true, message: '请输入项目名-英文字母', trigger: 'blur' },
                    ],
                    jobcontent: [
                        { required: true, message: '请备注上线内容', trigger: 'blur' },

                    ],

                    onlineDateTime: [
                        {  message: '请选择上线时间', trigger: 'change' }
                    ],
                    onlineItems: [
                        { required: true, message: '请选择上线项目', trigger: 'change' }
                    ],
                    dbChooseUniqueRules: [
                        { required: true,validator: dbChooseUnique, trigger: 'blur'}
                    ],
                    sqlStatementRules: [
                        { required: true, message: '请输入SQL', trigger: 'blur' },
                    ],
                    testRePortCheckRules: [
                        { required: true, validator: reportUpload, trigger: 'blur' },
                    ],


                },
                selectVisible: false,
                selectVaule: '',
                dbChoice: [],
                itemsChoice: [],
            }
        },
        methods: {
            createDeployJob(formName) {

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        // let jobparm = {
                        //     title: this.newjob.title,
                        //     content: this.newjob.jobcontent,
                        //     onlinetime: this.newjob.onlineTime,
                        //     itemlist: this.newjob.onlineItems.join(" "),
                        //     dblist : this.newjob.databaseTags.join(" "),
                        //     sqllist :this.newjob.databaseSql.join("|"),
                        // }
                        //
                        // AddDeployJob(jobparm).then((res) => {
                        //     console.log("debug here")
                        //     console.log(res.code)
                        //     if (res.code === 400) {
                        //         this.$message({
                        //             message: "Warning: 创建失败 " + res.message ,
                        //             type: 'success',
                        //             duration: 1000,
                        //         });
                        //     }else {
                        //         //this.$emit('close_tab')
                        //         this.$router.push('/deploy/joblist')
                        //     }
                        // })

                        let wfForm = new FormData();
                        wfForm.append( 'title', this.newjob.title,)
                        wfForm.append( 'content', this.newjob.jobcontent,)
                        wfForm.append( 'onlinetime', this.newjob.onlineTime,)
                        wfForm.append( 'itemlist', this.newjob.onlineItems.join(" "),)
                        wfForm.append(  'dblist' , this.newjob.databaseTags.join(" "),)
                        wfForm.append( 'sqllist' , this.newjob.databaseSql.join("|"))

                        Object.entries(this.testReportList).forEach(file => {
                            // file[1].forEach(item => {
                            //     wfForm.append('files', item.raw)
                            //     wfForm.append(item.name, file[0])
                            // })
                            wfForm.append('filename', file[1].name)
                            wfForm.append('file', file[1].raw)
                            // console.log()
                            // console.log(file[1].raw)
                        })
                        console.log("1.1.1.1.1.")
                        console.log(wfForm.get('filename'))
                        console.log(wfForm.get('file'))

                        AddDeployJob(wfForm).then((res) => {
                            console.log("debug here")
                            console.log(res)
                            this.$router.push('/deploy/joblist')
                        })


                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });






            },
            cancelCreate(){
                this.$router.push('/deploy/joblist')
            },
            handleClose(index) {
                this.newjob.databaseTags.splice(index, 1);
                this.newjob.databaseSql.splice(index, 1);
            },

            showSelect() {
                this.selectVisible = true;
                /*
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
                */
            },

            handleSelectConfirm() {
                let selectVaule = this.selectVaule;
                if (selectVaule) {
                    this.newjob.databaseTags.push(selectVaule);
                    this.newjob.databaseSql.push("");
                }
                this.selectVisible = false;
                this.selectVaule = '';
            },
            chooseDbs(){
                getDbList().then((res) => {
                        console.log(res.data.dblist)
                        this.dbChoice = res.data.dblist
                        //this.userList = res.data.users
                        //this.dbs = res.data.dblist
                    }
                )
            },
            chooseItems(){
                getDeployItems().then((res) => {
                        console.log(res.data.items)
                        this.itemsChoice = res.data.items
                        //this.userList = res.data.users
                        //this.dbs = res.data.dblist
                    }
                )
            },
            isRepeat(arr) {
                let hash = {};
                for (var i=0;i < arr.length;i++) {
                    if (hash[arr[i]]){
                        return true;
                    }
                    hash[arr[i]] = true;
                }
                return false;
            },
            containEmpty(arr) {
                if (arr.length === 0) {
                    return false
                }
                for (var i=0;i < arr.length;i++) {
                    if (arr[i].trim() === "") {
                        return true
                    }
                }
                return false
            },

            beforeAvatarUpload(file) {
                const isLt500K = file.size / 1024 / 1024 < 2;
                if (!isLt500K) {
                    this.$message.error('上传文件大小不能超过 500Kb!');
                }
                return isLt500K
            },
            handleAvatarSuccess(res, file) {
                //console.log(res.filename)
                //console.log(file)
                this.$message({
                    message: " 上传成功" ,
                    type: 'success'
                });
            },
            handleAvatarError(res) {
                this.$message({
                    message: "上传失败" + res.message ,
                    type: 'success'
                });

            },
            handleExceed(files, fileList) {
                // console.log(fileList)
                this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            fileChange(file,fileList) {
                console.log(file, fileList);
                this.testReportList = fileList;

                // this.files[''] = fileList;
            },



            testrepeat() {
                let self = this
                console.log(self.newjob.databaseTags)
                console.log(self.isRepeat(self.newjob.databaseTags))

            },

        }
    }
</script>


<style>
    #cicd-newdeployment .el-tag + .el-tag {
        margin-left: 10px;

    }
    #cicd-newdeployment .el-tag {

        color:#409eff;
        background-color: rgba(64,158,255,.1);
        align-content: center;
    }

    #cicd-newdeployment .button-new-tag {

        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
    }
    #cicd-newdeployment .input-new-tag {
        width: 200px;
        margin-left: 10px;
        vertical-align: bottom;
    }
    #cicd-newdeployment .el-alert--warning.is-light {
        background-color: white;
        border-right:1px solid ;
        border-bottom:1px solid ;
        border-top:1px solid ;
        border-left:3px solid ;

    }
    #cicd-newdeployment ol {
        margin: 0px;
    }
</style>